package com.zhushenwudi.hmutils.net;

import com.google.gson.JsonParseException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import ohos.data.preferences.Preferences;
import retrofit2.HttpException;

import java.net.UnknownHostException;

public abstract class RequestBaseObserver<V extends HttpBean> implements Observer<V> {
    private final static String NET_ERROR = "无法连接到互联网";
    private final static String SERVER_ERROR = "服务繁忙，请稍后再试";
    private final static String DNS_ERROR = "DNS异常";
    private final static String DATA_ERROR = "请联系管理员查看数据格式";
    private Preferences sp;

    public RequestBaseObserver() {
    }

    public RequestBaseObserver(final Preferences sp) {
        this.sp = sp;
    }

    @Override
    public void onSubscribe(Disposable disposable) {
        // 订阅请求时开启Loading界面
        changeStatus(true);
    }

    @Override
    public void onNext(V t) {
        if (t.code == 0 || t.code == 200) {
            onSuccess(t);
            return;
        }
        onError(t.message);
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof NoNetworkException) {
            onError(NET_ERROR);
        } else if (e instanceof HttpException) {
            onError(SERVER_ERROR);
        } else if (e instanceof UnknownHostException) {
            onError(DNS_ERROR);
        } else if (e instanceof JsonParseException) {
            onError(DATA_ERROR);
        } else {
            onError(e.getMessage());
        }
    }

    @Override
    public void onComplete() {
        // 请求结束时关闭Loading界面
        changeStatus(false);
    }

    public abstract void onSuccess(V t);

    public abstract void onError(String msg);

    /**
     * 修改加载弹窗状态
     *
     * @param status true: 显示; false: 隐藏
     */
    private void changeStatus(boolean status) {
        sp.putBoolean("pending", status);
        sp.flushSync();
    }

    // 自定义无网络异常
    public static class NoNetworkException extends RuntimeException {
    }
}
